package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;

import dao.ComputerDAO;
import entity.Computer;

public class ComputerDAOJdbcImpl implements ComputerDAO {

	@Override
	public List<Computer> findAll() throws Exception {
		List<Computer> computers=new ArrayList<Computer>();
		String sql="select * from computer";
		Connection con=null;
		Statement stm=null;
		ResultSet rs = null;
		try {
			con=DBUtil.openInThread();
			stm=con.createStatement();
			rs=stm.executeQuery(sql);
			while(rs.next()){
				Computer c = new Computer();
				c.setId(rs.getLong("id"));
				c.setModel(rs.getString("model"));
				c.setPicName(rs.getString("picName"));
				c.setPrice(rs.getDouble("price"));
				c.setProdDesc(rs.getString("prodDesc"));
				computers.add(c);
			}
			DBUtil.close(null, stm, rs);
		} finally {
			DBUtil.closeInThread();
		}
		return computers;
	}

	@Override
	public Computer findById(long id) throws Exception {
		Computer c = new Computer();
		String sql="select * from computer where id=?";
		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs = null;
		try {
			con=DBUtil.openInThread();
			pst=con.prepareStatement(sql);
			pst.setInt(1, (int) id);
			rs=pst.executeQuery();
			if(rs.next()){
				c.setId(rs.getLong("id"));
				c.setModel(rs.getString("model"));
				c.setPicName(rs.getString("picName"));
				c.setPrice(rs.getDouble("price"));
				c.setProdDesc(rs.getString("prodDesc"));
			}
			DBUtil.close(null, pst, rs);
		} finally {
			DBUtil.closeInThread();
		}
		return c;
	}

	@Override
	public void save(Computer c) throws Exception {
	}

}
